<template>
	<div class='choose-files'>
		<el-upload
			action="https://jsonplaceholder.typicode.com/posts/"
			list-type="picture-card"
			:on-preview="onclickReview"
			:file-list="fileList"
			:auto-upload="false"
			:limit="props.limit"
			@change="onChangeFiles"
			@remove="onChangeFiles"
		>
			<el-icon><Plus /></el-icon>
		</el-upload>
		<!-- 图片预览 -->
		<el-image-viewer
			v-if="previewUrl"
			ref="PreviewRef"
			:url-list="[previewUrl]"
			@close="previewUrl=''"
		/>
	</div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import { Plus } from '@element-plus/icons-vue'
// eslint-disable-next-line no-unused-vars
import type { UploadProps, UploadUserFile } from 'element-plus'

interface Props {
  limit: number,
  files: UploadUserFile[]
}
const props = withDefaults(defineProps<Props>(), {
  limit: 1,
  files: () => []
})
const emit = defineEmits<{
  (e: 'changeFiles', val: any[]): void
}>()

const fileList = ref<UploadUserFile[]>(props.files)

/* 预览图片 */
const previewUrl = ref('')
const onclickReview: UploadProps['onPreview'] = (file) => {
  if (!file.url) {
    return
  }
  previewUrl.value = file.url
}

/**
 * 图片改变回调，将结果传给父组件
 */
const onChangeFiles = () => {
  emit('changeFiles', fileList.value.map(item => item.raw))
}
</script>
